package com.dms.modules.order.service.impl;

import com.dms.common.exception.BusinessException;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.service.OrderPaymentService;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.payment.entity.AlipayOrder;
import com.dms.modules.payment.service.AlipayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderPaymentServiceImpl implements OrderPaymentService {

    private final OrderService orderService;
    private final AlipayService alipayService;

    @Override
    public String createPayment(Long orderId, String paymentType) {
        // 获取订单信息
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 根据支付方式创建支付订单
        switch (paymentType.toLowerCase()) {
            case "alipay":
                return createAlipayPayment(order);
            case "wechat":
                return createWechatPayment(order);
            default:
                throw new BusinessException("不支持的支付方式：" + paymentType);
        }
    }

    private String createAlipayPayment(Order order) {
        // 创建支付宝订单
        AlipayOrder alipayOrder = new AlipayOrder();
        alipayOrder.setOrderNo(order.getOrderNo());
        alipayOrder.setTotalAmount(String.format("%.2f", order.getTotalAmount()));
        alipayOrder.setSubject("订单支付-" + order.getOrderNo());
        alipayOrder.setTradeStatus("WAIT_BUYER_PAY");
        alipayOrder.setUserId(order.getUserId());
        alipayOrder.setMerchantId(order.getMerchantId()); // 设置商家ID

        // 调用支付宝接口创建支付订单
        return alipayService.createPayment(alipayOrder);
    }

    private String createWechatPayment(Order order) {
        // TODO: 实现微信支付
        throw new BusinessException("微信支付暂未实现");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handlePaymentCallback(String paymentType, String orderNo, String paymentNo, boolean success) {
        try {
            // 更新订单状态
            Order order = orderService.lambdaQuery()
                .eq(Order::getOrderNo, orderNo)
                .one();

            if (order == null) {
                log.error("订单不存在：{}", orderNo);
                return false;
            }

            if (success) {
                // 更新订单状态为已支付
                order.setStatus(1); // 假设1表示已支付状态
                order.setPaymentNo(paymentNo);
                order.setPaymentTime(java.time.LocalDateTime.now());
                orderService.updateById(order);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("处理支付回调失败", e);
            return false;
        }
    }

    @Override
    public boolean queryPaymentStatus(Long orderId, String paymentType) {
        // 获取订单信息
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 根据支付方式查询支付状态
        switch (paymentType.toLowerCase()) {
            case "alipay":
                return queryAlipayStatus(order);
            case "wechat":
                return queryWechatStatus(order);
            default:
                throw new BusinessException("不支持的支付方式：" + paymentType);
        }
    }

    private boolean queryAlipayStatus(Order order) {
        // 查询支付宝订单状态
        AlipayOrder alipayOrder = alipayService.queryOrder(order.getOrderNo());
        if (alipayOrder == null) {
            return false;
        }

        // 更新订单状态
        if ("TRADE_SUCCESS".equals(alipayOrder.getTradeStatus())) {
            order.setStatus(1);
            order.setPaymentNo(alipayOrder.getTradeNo());
            order.setPaymentTime(alipayOrder.getPayTime());
            orderService.updateById(order);
            return true;
        }

        return false;
    }

    private boolean queryWechatStatus(Order order) {
        // TODO: 实现微信支付状态查询
        throw new BusinessException("微信支付暂未实现");
    }
} 